<?php
/**
 * (logic) （临时转正式）Payment退货费
 */
namespace App\Logic\MonthlyReport\ParseTmp;

use App\Models\Basics\SysCountry;
use App\Models\MonthlyReport\Payment\PaymentReFee;
use App\Models\MonthlyReport\Tmp\TmpPReFee;
class ParsePaymentReFee
{
    public static function exeParse($date){
        //临时
        $lines = TmpPReFee::query()->selectRaw('country,sku,sum(total) as total')
            ->where('report_date',$date)
            ->whereNotNull('sku')
            ->groupBy(['country','sku'])
            ->get();
        $s = TmpPReFee::query()->selectRaw('country,sku,sum(quantity) as quantity')
            ->where('report_date',$date)
            ->where('product_sales','<>',0)
            ->whereNotNull('sku')
            ->groupBy(['country','sku'])
            ->get();
        $data = [];
        foreach ($s as $_s){
            $data[$_s->country.'_'.$_s->sku] = $_s->quantity;
        }
        $i = 0;
        $num = 100;
        $country = [];
        while(true){
            if($lines->isEmpty())break;
            $_lines = $lines->splice($i,$num);
            foreach ($_lines as $line){
                if(!array_key_exists($line->country,$country)){
                    $countryId = SysCountry::getIdByCountry($line->country);
                    $country[$line->country] = $countryId ?: 0;
                }
                $key = $line->country.'_'.$line->sku;
                if(array_key_exists($key,$data)){
                    $quantity = $data[$key];
                }else{
                    $quantity = 0;
                }
                //正式
                PaymentReFee::query()->updateOrCreate(['report_date' => $date,
                    'country_id' => $country[$line->country],
                    'seller_sku' => $line->sku],
                    ['quantity' => $quantity,'total' => $line->total]);
            }
        }
    }
}
